#include <stdlib.h>
#include <stdio.h>

#include "idmgr.h"

/****************************************************************************/
void init_id_mgr(struct id_mgr_table* idmgr, UINTID minid)
{
  idmgr->m_min_id = minid;
  idmgr->m_max_id = minid;
  idmgr->m_id_recycle = NULL;
}

UINTID getid_id_mgr(struct id_mgr_table* idmgr)
{
  UINTID id = 0;
  struct id_recycle_item *pFirstItem = NULL;

  if ( idmgr == NULL )
	return 0;

  pFirstItem = idmgr->m_id_recycle;

  if (NULL == pFirstItem){
	id = idmgr->m_max_id;
	idmgr->m_max_id += 1;
  }//if
  else {
	id = pFirstItem->m_id;
	idmgr->m_id_recycle = pFirstItem->m_next;
	free(pFirstItem);
	pFirstItem = NULL;
  }//else

  return id;
}

/****************************************************************************/
void releaseid_id_mgr(struct id_mgr_table *idmgr, UINTID id)
{
  struct id_recycle_item *newitem = NULL;
  struct id_recycle_item *pitem = NULL;

  if (id == idmgr->m_max_id){
	if (idmgr->m_max_id != idmgr->m_min_id)
		 idmgr->m_max_id -= 1;
  }
  else if (id < idmgr->m_max_id && id >= idmgr->m_min_id){
	newitem = (struct id_recycle_item*)malloc(sizeof(struct id_recycle_item));
	if (newitem == NULL){
		//printf("No enough memory in releaseid_id_mgr(...)");
		return ;
	}//if
	newitem->m_id = id;
	newitem->m_next = NULL;

	if (idmgr->m_id_recycle == NULL ){
		idmgr->m_id_recycle = newitem;
	}//if
	else{
		pitem = idmgr->m_id_recycle;
		if (newitem->m_id < pitem->m_id){
			newitem->m_next = pitem;
			idmgr->m_id_recycle = newitem;
	  	}//if
		else {
			while (pitem->m_next != NULL) {
				if (newitem->m_id < pitem->m_next->m_id){
					newitem->m_next = pitem->m_next;
					pitem->m_next = newitem;
					break;
				}//if
				pitem = pitem->m_next;
			}//while
			
			if (pitem->m_next == NULL)
				pitem->m_next = newitem;
			
	  	}//else
	}//else
	
  }//else if
}//if

void clear_id_mgr(struct id_mgr_table *idmgr)
{
  idmgr->m_min_id = 0;
  idmgr->m_max_id = 0;
  
  struct id_recycle_item* pitem = idmgr->m_id_recycle;
  while(NULL != pitem){
	idmgr->m_id_recycle = pitem->m_next;
	free(pitem);
	pitem = idmgr->m_id_recycle;
  }

  return;
}
/****************************************************************************/
/*
void print_recycle(struct id_mgr_table *idmgrtbl)
{
  struct id_recycle_item *p;

  p = idmgrtbl->m_id_recycle;

  printf("recycle: ");
  while (p != NULL){
	printf("%d ", p->m_id);
	p = p->m_next;
  }
  printf("\n");
}
*/

/****************************************************************************/
